package com.example.platform.web.config;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * 新的加密方式
 */
public class AesSecurityUtil {
    public static final int GCM_TAG_LENGTH = 16;
    public static final int GCM_IV_LENGTH = 12;
    public static final int AES_KEY_SIZE = 256;
    public static final String ALGORITHM_AES = "AES";
    public static final String CIPHER_TRANSFORM = "AES/GCM/NoPadding";
    private static final String KEY="083080D3D0C521C02CD3AE213463D09EA50DFF914677FAB9E22F18F9C28A3B9";


    //加密函数
    public static String encrypt(String textData) {
        try {
            byte[] plainText=textData.getBytes();
            byte[] raw=getRawKey(KEY.getBytes());
            byte[] nonce = new byte[GCM_IV_LENGTH];
            Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORM);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM_AES);
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec,gcmParameterSpec);
            byte[] cipherText = cipher.doFinal(plainText);
            StringBuilder stringBuilder = new StringBuilder();
            for (byte b : cipherText) {
                stringBuilder.append(String.format("%02x", b));
            }
            return stringBuilder.toString();
        }catch (Exception e){

            e.printStackTrace();
            return null;
        }
    }

    //解密函数
    public static String decrypt(String textData ) {
        try {
            byte[] cipherText = toByte(textData);
            byte[] raw=getRawKey(KEY.getBytes());
            byte[] nonce = new byte[GCM_IV_LENGTH];
            Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORM);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM_AES);
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec,gcmParameterSpec);
            byte[] plainText = cipher.doFinal(cipherText);
            return new String(plainText);

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    public static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
        return result;
    }



    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM_AES);
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        kgen.init(AES_KEY_SIZE, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }


    /**
     * 验证密码
     *
     * @param plainPassword 明文密码
     * @param password      密文密码
     * @return 验证成功返回true
     */

    public  static boolean checkPassword(String plainPassword, String password){
        boolean  check=false;
        String  cipherText = encrypt(plainPassword);
        if(password.equals(cipherText)){
            check=true;
        }
        return check;
    }


    /**
     * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
     */
    public static String entryptPassword(String plainPassword) {

        return  encrypt(plainPassword);
    }


    //-- User Service --//

    /**
     * 验证密码
     *
     * @param plainPassword 明文密码
     * @param password      密文密码
     * @return 验证成功返回true
     */
    public static boolean validatePassword(String plainPassword, String password) {

        return  checkPassword(plainPassword,password);
    }

    public static void main(String[] args) {
            String originalText = "123456";
            System.out.println("原始密码: " + originalText);
            String  cipherText = encrypt(originalText);
            System.out.println("加密: " +cipherText);
            String plainText = decrypt(cipherText);
            System.out.println("解密: " +plainText);
    }
}
